#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : DomainApi.py
@Time : 2025/2/24 13:40
@Author: Wangwc
@Describe:  域服务相关接口
"""
import time

from utils.requests_tools import HttpRequest, check_response, retry_func
from utils.login import Login
from commons.logger import log
from utils.ssh_tools import create_ssh_client_as_root, create_raid_with_shell

# TODO 当前模块的配置文件名称，配置在config目录下
config_name = 'user.ini'

assert_message = {'code': 200, 'msg': 'success'}
login = Login(config_name=config_name)
token = login.login()


class DomainApi:

    def __init__(self, u_token, configname=config_name):
        self.http = HttpRequest(configname, u_token=u_token)

    @check_response(ext="data.result", check=assert_message)
    def join_domain_test(self, addr, dns_addr, account, password, domain_type=0, dcip_fqdn="", update_period=1440,
                    uid_gid_convert=False, base_dn="", encryption_type=0,
                    certificate_info={"certificate": "", "private_key": ""}, exclusive=False, use_local_config=False):
        """
        加入AD域测试
        :param addr: 域地址
        :param dns_addr: DNS地址
        :param account: 域账号
        :param password: 域密码
        :param domain_type: 域类型
        :param certificate_info: 证书信息
        :return:
        """
        log.debug("开始执行加入AD域操作")
        path = "/ugreen/v1/domain/join/test"
        params = {"exclusive":exclusive, "use_local_config": use_local_config}
        data = {"domain_type": domain_type, "addr": addr, "dns_addr": dns_addr, "account": account,
                "password": password, "dcip_fqdn": dcip_fqdn, "update_period": update_period, "uid_gid_convert": uid_gid_convert,
                "base_dn": base_dn, "encryption_type":encryption_type, "certificate_info": certificate_info,
                "exclusive": exclusive, "use_local_config": use_local_config}
        try:
            response = self.http.post(path,json=data,params=params)
            return response
        except Exception as e:
            log.error(f"在加入AD域过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def join_domain(self, addr, dns_addr, account, password, domain_type=0, dcip_fqdn="", update_period=1440,
                    uid_gid_convert=False, base_dn="", encryption_type=0,
                    certificate_info={"certificate": "", "private_key": ""}, exclusive=False, use_local_config=False):
        """
        加入AD域
        :param addr: 域地址
        :param dns_addr: DNS地址
        :param account: 域账号
        :param password: 域密码
        :param domain_type: 域类型
        :param certificate_info: 证书信息
        :return:
        """
        log.debug("开始执行加入AD域操作")
        path = "/ugreen/v1/domain/join"
        data = {"domain_type": domain_type, "addr": addr, "dns_addr": dns_addr, "account": account,
                "password": password, "dcip_fqdn": dcip_fqdn, "update_period": update_period,
                "uid_gid_convert": uid_gid_convert,
                "base_dn": base_dn, "encryption_type": encryption_type, "certificate_info": certificate_info,
                "exclusive": exclusive, "use_local_config": use_local_config}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在加入AD域过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def exit_domain(self, x_curpass_token,reserve_user_home=True):
        """
        退出AD域
        :param reserve_user_home: 是否保留用户家目录
        :param x_curpass_token: x_curpass_token信息
        :return:
        """
        log.debug("开始执行加入AD域操作")
        path = "/ugreen/v1/domain/exit"
        data = {"reserve_user_home":reserve_user_home}
        headers = {"x-curpass-token":x_curpass_token}
        try:
            response = self.http.post(path, json=data,headers=headers)
            return response
        except Exception as e:
            log.error(f"在加入AD域过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain_userlist(self, keyword='', page=0,size=20):
        """
        查询域用户列表
        :param keyword: 关键字
        :return: 用户列表信息
        """
        log.debug("开始执行查询域用户列表操作")
        path = "/ugreen/v1/domain/userlist"
        params = {"keyword": keyword, "page": page, "size": size}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在查询域用户列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain_grouplist(self, keyword='', page=0, size=20):
        """
        查询域用户组列表
        :param keyword: 关键字
        :return: 域用户组列表信息
        """
        log.debug("开始执行查询域用户组列表操作")
        path = "/ugreen/v1/domain/grouplist"
        params = {"keyword": keyword, "page": page, "size": size}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在查询域用户组列表过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def update_domain_data(self):
        """
        同步域数据
        :return:
        """
        log.debug("开始执行同步域数据操作")
        path = "/ugreen/v1/domain/updatedata"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在同步域数据过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain_test_result(self):
        """
        查询测试结果
        :return:
        """
        log.debug("开始执行查询测试结果操作")
        path = "/ugreen/v1/domain/join/test"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在查询测试结果过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain_dnsaddrs(self):
        """
        查询系统dns地址
        :return:
        """
        log.debug("开始执行查询系统dns地址操作")
        path = "/ugreen/v1/domain/dnsaddrs"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在查询系统dns地址过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.config", check=assert_message)
    def get_domain_join_config(self):
        """
        查询加入域的配置
        :return:
        """
        log.debug("开始执行查询加入域的配置操作")
        path = "/ugreen/v1/domain/join/config"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在查询加入域的配置过程中出现异常，异常信息: {e}")
            raise

    def check_domain_status(self,status=2,timeout=120):
        """
        校验domain的状态是否符合预期
        """
        log.debug(f"开始校验domain状态并等待，预期状态: {status}，最大等待时间: {timeout} 秒")
        try:
            elapsed_time = 0
            while elapsed_time < timeout:
                result = self.get_domain_join_config()
                domain_status = result.get('join_domain_status')
                log.info(f"当前获取到的 domain 状态为: {domain_status}")
                if domain_status == status:
                    log.debug(f"在 {elapsed_time} 秒内达到预期状态 {status}")
                    return True
                time.sleep(10)
                elapsed_time += 10
                log.info(f"domain 状态为 {domain_status}，等待 10 秒后继续校验，已等待 {elapsed_time} 秒")
            raise TimeoutError(f"等待 {timeout} 秒后仍未达到预期状态 {status}")
        except TimeoutError as e:
            log.error(f"等待超时: {e}")
            raise
        except Exception as e:
            log.error(f"获取 domain 状态过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain_user_info(self,uid):
        """
        查询域用户信息
        :return:
        """
        log.debug("开始执行查询域用户信息操作")
        path = "/ugreen/v1/domain/user/info"
        params = {"uid": uid}
        try:
            response = self.http.get(path,params=params)
            return response
        except Exception as e:
            log.error(f"在查询域用户信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def get_domain_group_info(self, gid):
        """
        查询域用户组信息
        :param gid:组id信息
        :return:
        """
        log.debug("开始执行查询域用户组信息操作")
        path = "/ugreen/v1/domain/group/info"
        params = {"gid": gid}
        try:
            response = self.http.get(path, params=params)
            return response
        except Exception as e:
            log.error(f"在查询域用户组信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def edit_domain_user_info(self, uid,username,role="users",enable_home_dir=True,unit=1,dir_quota=0):
        """
        编辑域用户信息
        :param uid:用户id信息
        :param username:用户名
        :param role:用户角色
        :param enable_home_dir:是否启用家目录
        :param unit:单位
        :param dir_quota:目录配额
        :return:
        """
        log.debug("开始执行查询域用户组信息操作")
        path = "/ugreen/v1/domain/user/info"
        data = {"uid":uid,"role":role,"enable_home_dir":enable_home_dir,"username":username,"unit":unit,"dir_quota":dir_quota}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在查询域用户组信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def get_domain_group_permission(self,gid):
        """
        获取域用户组权限信息
        :param gid:用户组id信息
        :return: 域用户组权限信息
        """
        log.debug("开始执行获取域用户组权限信息操作")
        path = f"/ugreen/v1/group/permission/{gid}"
        try:
            response = self.http.get(path)
            return response
        except Exception as e:
            log.error(f"在获取域用户组权限信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def edit_domain_group_permission(self, gid, file_list):
        """
        编辑域用户组权限信息
        :param gid:用户组id信息
        :return:
        """
        log.debug("开始执行编辑域用户组权限信息操作")
        path = f"/ugreen/v1/group/permission/{gid}"
        data = {"list": file_list}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在编辑域用户组权限信息过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def update_domain_config(self,update_period=1440):
        """
        更新域配置
        :param update_period:更新周期
        :return:
        """
        log.debug("开始执行更新域配置操作")
        path = f"/ugreen/v1/domain/updateconfig"
        data = {"update_period":update_period}
        try:
            response = self.http.post(path, json=data)
            return response
        except Exception as e:
            log.error(f"在更新域配置过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data", check=assert_message)
    def endprogress_domain_join(self):
        """
        结束加入域流程
        :return:
        """
        log.debug("开始执行结束加入域流程操作")
        path = f"/ugreen/v1/domain/join/endprogress"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在结束加入域流程过程中出现异常，异常信息: {e}")
            raise

    @check_response(ext="data.result", check=assert_message)
    def check_domain_user_enable_home(self):
        """
        检查域用户是否开启home目录
        :return:
        """
        log.debug("开始执行检查域用户是否开启home目录操作")
        path = f"/ugreen/v1/domain/user/enable/home"
        try:
            response = self.http.post(path)
            return response
        except Exception as e:
            log.error(f"在检查域用户是否开启home目录过程中出现异常，异常信息: {e}")
            raise

if __name__ == "__main__":
    pass
